Repository navigation
fix(provider): bound Gemma-4 checkpoint-capture to stop the Metal live-resource (499000) leak - #374
Conversation
…e-resource (499000) leak
Heterogeneous models (Gemma-4) use the `.checkpoint` prefix-cache tier. The
capture hook spawned an UNBOUNDED `Task { await mgr.store(...) }` per
checkpoint boundary, each pinning a live per-layer KV snapshot (≈ layers × 2
Metal buffers) until the single `PrefixCacheManager` actor — serialized behind
AES-GCM + fsync and against every lookup/materialize — ran it. Under sustained
traffic the actor falls behind, the detached Tasks queue, their live snapshots
accumulate, and the live Metal buffer COUNT (not bytes/cache) climbs to the
`iogpu.rsrc_limit` ceiling (~499000) → `[metal::malloc] Resource limit
exceeded` crash. The mlx/mlx-c count-aware cache trims cannot help: these
buffers are LIVE, not cached, and the idle-gated `Memory.clearCache()` never
fires under load.
Bound the live snapshots in flight instead:
- CheckpointCapturePipeline — a bounded, single-consumer AsyncStream
(`bufferingNewest(max-in-flight)`, default 2, env-tunable via
DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT) that drops the surplus snapshot on full
and releases it. Capture is best-effort cache-warming, so a drop only costs
a future cache miss, never correctness. This caps retained live snapshots to
a small constant regardless of how far behind the manager falls.
- Admission gate — skip capture when the live MLX resource count exceeds 70%
of `Memory.resourceLimit` (guards `resourceLimit == 0`), so we stop feeding
the leak exactly when it matters.
- Teardown — `stopCurrentEngine` (and the superseded-load bailouts) now drain
and cancel the pipeline, releasing any retained snapshots so nothing leaks
across model swaps.
The decode path, KV-cache classes, and the manager's persistence logic are
unchanged; the only behavior change is bounding capture. Adds a focused unit
test proving the in-flight bound holds and overflow is dropped, not queued.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 4 finding(s) (3 blocking)
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61— NSLock allocation on every pipeline instance for lightweight counters- Suggestion: Consider using atomic operations (OSAtomicIncrement32 or std::atomic equivalent) for simple counters instead of NSLock to reduce allocation overhead
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:120-122— Lock acquisition in getter methods called from hot paths- Suggestion: Cache counter values or use lock-free atomic operations since these are simple integer counters accessed frequently
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258— Redundant pipeline shutdown calls in multiple cleanup paths- Suggestion: Add a shutdown flag to make shutdown() idempotent and avoid redundant work in cleanup paths
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:218— captureResourcePressureHigh() called on every checkpoint capture- Suggestion: Cache the resource pressure check result for a short duration (e.g., 100ms) since MLX.Memory counters don't change rapidly
Type_diligence — ✅ No issues found
Additive_complexity — 4 finding(s) (1 blocking)
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258— Identical cleanup pattern repeated 4 times with same identity checks- Suggestion: Extract a helper method
cleanupBuildArtifacts(build:)to eliminate the repeated identity-checked cleanup pattern
- Suggestion: Extract a helper method
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61— Generic pipeline class when only one concrete type is used- Suggestion: Consider making this concrete for CheckpointCapture since no other payload types are anticipated
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:69-71— Lock-guarded counters for simple statistics that could be atomic- Suggestion: Use OSAtomicIncrement64 or similar atomic operations instead of NSLock for simple counters
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1185-1188— Complex capture pipeline construction logic embedded in engine builder- Suggestion: Move the capture pipeline factory logic to a dedicated builder class or the CheckpointCapturePipeline itself
8 finding(s) total, 4 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| /// fixes the 499000 leak. | ||
| /// | ||
| /// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable | ||
| /// without MLX (the production instantiation is `Payload == CheckpointCapture`). |
There was a problem hiding this comment.
🔵 [INFO] ⚡ NSLock allocation on every pipeline instance for lightweight counters
💡 Suggestion: Consider using atomic operations (OSAtomicIncrement32 or std::atomic equivalent) for simple counters instead of NSLock to reduce allocation overhead
📊 Score: 2×3 = 6 · Category: Unbounded allocations
| @@ -251,6 +258,7 @@ public actor BatchScheduler { | |||
| if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] } | |||
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Redundant pipeline shutdown calls in multiple cleanup paths
💡 Suggestion: Add a shutdown flag to make shutdown() idempotent and avoid redundant work in cleanup paths
📊 Score: 3×3 = 9 · Category: Repeated work
| "checkpoint capture pipeline: max-in-flight \(maxInFlight) (drop-on-full), admission-gate at \(Int(captureResourcePressureFraction * 100))% of Metal resource limit") | ||
| let hook: CheckpointCaptureHook = { [pipeline] prefixTokens, length, caches in | ||
| // 1. Admission gate. Returning here lets the `caches` argument go | ||
| // out of scope → its Metal buffers free immediately. |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ captureResourcePressureHigh() called on every checkpoint capture
💡 Suggestion: Cache the resource pressure check result for a short duration (e.g., 100ms) since MLX.Memory counters don't change rapidly
📊 Score: 2×4 = 8 · Category: Repeated work
| @@ -251,6 +258,7 @@ public actor BatchScheduler { | |||
| if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] } | |||
There was a problem hiding this comment.
🔵 [INFO] 🧩 Identical cleanup pattern repeated 4 times with same identity checks
💡 Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-checked cleanup pattern
📊 Score: 2×3 = 6 · Category: duplicate logic
| /// fixes the 499000 leak. | ||
| /// | ||
| /// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable | ||
| /// without MLX (the production instantiation is `Payload == CheckpointCapture`). |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Generic pipeline class when only one concrete type is used
💡 Suggestion: Consider making this concrete for CheckpointCapture since no other payload types are anticipated
📊 Score: 2×2 = 4 · Category: over-abstraction
| // Lightweight counters (lock-guarded; read from tests / future telemetry). | ||
| private let statsLock = NSLock() | ||
| private var _accepted = 0 |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Lock-guarded counters for simple statistics that could be atomic
💡 Suggestion: Use OSAtomicIncrement64 or similar atomic operations instead of NSLock for simple counters
📊 Score: 1×2 = 2 · Category: over-configuration
|
This PR fixes a Metal resource exhaustion crash (the "Gemma-4 499000 leak") by replacing an unbounded Trust Boundaries Touched
Threat AssessmentT-007 — Provider serves manipulated model outputs ( T-028 — Residual inference data in GPU memory after request completes ( T-041 — Cross-tenant prefix-cache sharing + TTFT timing oracle ( New Attack SurfaceDrop-on-overflow is silent to the consumer. This is not covered by an existing threat. Recommend adding a telemetry emission (heartbeat or metrics counter) for Open Findings ResolvedNone of the tracked SEC-* findings are resolved by this PR. SEC-007, SEC-016, SEC-017, SEC-035 remain open and are untouched. Summary of Concerns (Priority Order)
🔐 Threat model: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e593383fad
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for await payload in stream { | ||
| await consume(payload) |
There was a problem hiding this comment.
Honor cancellation before draining buffered captures
When a model is unloaded while this stream has buffered captures, shutdown() calls finish() and cancel(), but this loop never observes cancellation. AsyncStream continues yielding values that were already buffered after finish/cancel, so a backlogged consumer can keep holding and storing old-model KV snapshots after stopCurrentEngine has moved on to flush/deregister or load the next engine. That defeats the teardown guarantee and can overlap large Metal buffers across a model swap; break on Task.isCancelled before consuming buffered values, or explicitly discard the queue, so shutdown actually drops them.
Useful? React with 👍 / 👎.
|
Found 1 test failure on Blacksmith runners: Failure
|
…ion) CheckpointCapturePipeline.shutdown() calls finish() + cancel(), but an AsyncStream for-await loop does not observe Task cancellation on its own and finish() still delivers already-buffered payloads. The consumer therefore kept store()-ing buffered KV snapshots after a model swap had begun, pinning live Metal buffers across engines — the exact overlap teardown was meant to prevent. Honor cancellation inside the loop: once cancelled, keep pulling the buffered remainder (so the retained continuation does not strand it alive) but skip consume(), dropping the best-effort captures. Add a regression test proving only the in-flight capture runs after shutdown and nothing leaks.
|
Addressed the cancellation/teardown review point in a776a51: |
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 3 finding(s) (1 blocking)
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:86-89— AsyncStream with bufferingNewest policy may cause memory pressure under high load- Suggestion: Consider adding telemetry to monitor buffer utilization and dropped payloads to validate the capacity sizing in production
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:70-72— NSLock usage in stats tracking could cause contention on high-frequency submit calls- Suggestion: Replace NSLock with atomic operations (OSAtomicIncrement64 or similar) for simple counters to eliminate lock contention
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1945-1952— Synchronous shutdown and drain operations in stopCurrentEngine may block actor- Suggestion: Consider making capturePipeline shutdown asynchronous or use a detached task to avoid blocking the actor during engine teardown
Type_diligence — ✅ No issues found
Additive_complexity — 4 finding(s)
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258— Identical cleanup pattern repeated 4 times with same identity checks- Suggestion: Extract a helper method
cleanupBuildArtifacts(build:)to eliminate the repeated identity-check cleanup pattern
- Suggestion: Extract a helper method
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61— Generic type parameter adds complexity for single concrete use- Suggestion: Remove generic
<Payload: Sendable>and hardcodeCheckpointCapturesince there's only one production use case
- Suggestion: Remove generic
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:70-72— Lightweight counters with lock for simple integers- Suggestion: Use atomic operations or remove counters entirely if only used for testing
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:158-162— Environment variable tuning for internal buffer size- Suggestion: Remove env var tuning - the default of 2 is already conservative and this adds unnecessary configuration surface
7 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| of: Payload.self, | ||
| bufferingPolicy: .bufferingNewest(cap) | ||
| ) | ||
| self.continuation = continuation |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ AsyncStream with bufferingNewest policy may cause memory pressure under high load
💡 Suggestion: Consider adding telemetry to monitor buffer utilization and dropped payloads to validate the capacity sizing in production
📊 Score: 3×4 = 12 · Category: Unbounded allocations
| private let statsLock = NSLock() | ||
| private var _accepted = 0 | ||
| private var _dropped = 0 |
There was a problem hiding this comment.
🔵 [INFO] ⚡ NSLock usage in stats tracking could cause contention on high-frequency submit calls
💡 Suggestion: Replace NSLock with atomic operations (OSAtomicIncrement64 or similar) for simple counters to eliminate lock contention
📊 Score: 2×3 = 6 · Category: Blocking I/O on hot paths
| modelContainer = nil | ||
| tokenizer = nil | ||
| // Drain the bounded capture pipeline: the engine is stopped (no more | ||
| // capture hooks fire), so finish the stream and cancel the consumer. | ||
| // This releases any retained KV snapshots and stops an in-flight | ||
| // `mgr.store` from racing the index flush / accountant deregister below, | ||
| // and guarantees no snapshot (or consumer Task) leaks across a swap. | ||
| capturePipeline?.shutdown() |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Synchronous shutdown and drain operations in stopCurrentEngine may block actor
💡 Suggestion: Consider making capturePipeline shutdown asynchronous or use a detached task to avoid blocking the actor during engine teardown
📊 Score: 2×2 = 4 · Category: Blocking I/O on hot paths
| @@ -251,6 +258,7 @@ public actor BatchScheduler { | |||
| if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] } | |||
There was a problem hiding this comment.
🔵 [INFO] 🧩 Identical cleanup pattern repeated 4 times with same identity checks
💡 Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-check cleanup pattern
📊 Score: 2×3 = 6 · Category: duplicate logic
| /// fixes the 499000 leak. | ||
| /// | ||
| /// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable | ||
| /// without MLX (the production instantiation is `Payload == CheckpointCapture`). |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Generic type parameter adds complexity for single concrete use
💡 Suggestion: Remove generic <Payload: Sendable> and hardcode CheckpointCapture since there's only one production use case
📊 Score: 2×2 = 4 · Category: over-configuration
| private let statsLock = NSLock() | ||
| private var _accepted = 0 | ||
| private var _dropped = 0 |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Lightweight counters with lock for simple integers
💡 Suggestion: Use atomic operations or remove counters entirely if only used for testing
📊 Score: 1×2 = 2 · Category: over-abstraction
| // make sure the stream terminates and the consumer Task ends. | ||
| continuation.finish() | ||
| consumer.cancel() | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Environment variable tuning for internal buffer size
💡 Suggestion: Remove env var tuning - the default of 2 is already conservative and this adds unnecessary configuration surface
📊 Score: 1×2 = 2 · Category: over-configuration
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 3 finding(s) (1 blocking)
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:86-89— AsyncStream with bufferingNewest policy may still accumulate tasks under high contention- Suggestion: Consider adding explicit task cancellation tracking or using a semaphore-based approach to guarantee bounded concurrency
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:95-110— Consumer task processes payloads serially which could create backpressure- Suggestion: Consider parallel processing of payloads if the consume function is I/O bound, or document that this is intentionally serial
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1948-1952— Shutdown called multiple times in different code paths without idempotency check- Suggestion: Add explicit idempotency check in shutdown() method or ensure callers coordinate to avoid redundant shutdown calls
Type_diligence — ✅ No issues found
Additive_complexity — 5 finding(s) (1 blocking)
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:61— Generic pipeline class when only one concrete type is used- Suggestion: Consider making this non-generic since it's only used with CheckpointCapture. The generic abstraction adds complexity without clear benefit.
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:70-72— Lightweight counters with manual locking for simple statistics- Suggestion: Consider using atomic operations or removing these counters entirely if they're only for testing/debugging. The manual locking adds complexity for simple increment operations.
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:258— Identical cleanup pattern repeated 4 times in the file- Suggestion: Extract the identity-checked cleanup pattern into a helper method to reduce duplication and maintenance burden.
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:156-162— Environment variable parsing with fallback for simple integer- Suggestion: Consider using a simpler approach or removing the environment variable entirely since this is an internal tuning parameter with a reasonable default.
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Inference/CheckpointCapturePipeline.swift:95-108— Task cancellation check in data processing loop- Suggestion: Consider handling cancellation at the Task level rather than checking it inside the processing loop, which mixes cancellation concerns with data processing logic.
8 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| of: Payload.self, | ||
| bufferingPolicy: .bufferingNewest(cap) | ||
| ) | ||
| self.continuation = continuation |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ AsyncStream with bufferingNewest policy may still accumulate tasks under high contention
💡 Suggestion: Consider adding explicit task cancellation tracking or using a semaphore-based approach to guarantee bounded concurrency
📊 Score: 3×4 = 12 · Category: Unbounded goroutines
| // `for await` does NOT observe Task cancellation on its own. | ||
| // Without this guard we would `store(...)` old-model KV | ||
| // snapshots after a model swap has begun — pinning large live | ||
| // Metal buffers that must not overlap the next engine. | ||
| // | ||
| // We `continue` rather than `break`: the buffered remainder must | ||
| // still be pulled so each payload is released as it drains (the | ||
| // retained `continuation` keeps the stream's internal buffer — | ||
| // and anything stranded in it — alive). Skipping `consume` drops | ||
| // the captures (best-effort) without storing them; the finished | ||
| // stream then terminates the loop once its buffer empties. | ||
| if Task.isCancelled { continue } | ||
| await consume(payload) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Consumer task processes payloads serially which could create backpressure
💡 Suggestion: Consider parallel processing of payloads if the consume function is I/O bound, or document that this is intentionally serial
📊 Score: 2×3 = 6 · Category: Blocking I/O on hot paths
| // capture hooks fire), so finish the stream and cancel the consumer. | ||
| // This releases any retained KV snapshots and stops an in-flight | ||
| // `mgr.store` from racing the index flush / accountant deregister below, | ||
| // and guarantees no snapshot (or consumer Task) leaks across a swap. | ||
| capturePipeline?.shutdown() |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Shutdown called multiple times in different code paths without idempotency check
💡 Suggestion: Add explicit idempotency check in shutdown() method or ensure callers coordinate to avoid redundant shutdown calls
📊 Score: 2×2 = 4 · Category: Repeated work
| /// fixes the 499000 leak. | ||
| /// | ||
| /// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable | ||
| /// without MLX (the production instantiation is `Payload == CheckpointCapture`). |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Generic pipeline class when only one concrete type is used
💡 Suggestion: Consider making this non-generic since it's only used with CheckpointCapture. The generic abstraction adds complexity without clear benefit.
📊 Score: 2×3 = 6 · Category: over-abstraction
| private let statsLock = NSLock() | ||
| private var _accepted = 0 | ||
| private var _dropped = 0 |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Lightweight counters with manual locking for simple statistics
💡 Suggestion: Consider using atomic operations or removing these counters entirely if they're only for testing/debugging. The manual locking adds complexity for simple increment operations.
📊 Score: 2×2 = 4 · Category: over-configuration
| @@ -251,6 +258,7 @@ public actor BatchScheduler { | |||
| if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] } | |||
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Identical cleanup pattern repeated 4 times in the file
💡 Suggestion: Extract the identity-checked cleanup pattern into a helper method to reduce duplication and maintenance burden.
📊 Score: 3×4 = 12 · Category: duplicate logic
| deinit { | ||
| // Belt-and-suspenders: if the owner dropped us without `shutdown()`, | ||
| // make sure the stream terminates and the consumer Task ends. | ||
| continuation.finish() | ||
| consumer.cancel() | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Environment variable parsing with fallback for simple integer
💡 Suggestion: Consider using a simpler approach or removing the environment variable entirely since this is an internal tuning parameter with a reasonable default.
📊 Score: 2×2 = 4 · Category: over-configuration
| // `for await` does NOT observe Task cancellation on its own. | ||
| // Without this guard we would `store(...)` old-model KV | ||
| // snapshots after a model swap has begun — pinning large live | ||
| // Metal buffers that must not overlap the next engine. | ||
| // | ||
| // We `continue` rather than `break`: the buffered remainder must | ||
| // still be pulled so each payload is released as it drains (the | ||
| // retained `continuation` keeps the stream's internal buffer — | ||
| // and anything stranded in it — alive). Skipping `consume` drops | ||
| // the captures (best-effort) without storing them; the finished | ||
| // stream then terminates the loop once its buffer empties. | ||
| if Task.isCancelled { continue } | ||
| await consume(payload) | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Task cancellation check in data processing loop
💡 Suggestion: Consider handling cancellation at the Task level rather than checking it inside the processing loop, which mixes cancellation concerns with data processing logic.
📊 Score: 2×3 = 6 · Category: misplaced responsibility
Memory & reliability hardening: - 90% unified-memory cap + KV purge on unload + serve-while-load reservation (#363) - bounded checkpoint-capture pipeline, stops the Metal 499000 resource leak (#374) - resumable 4-bit model downloads + restart-safe detection (#372) - default-on [rsrc] resource telemetry in reports (#373 / mlx-swift-lm#42) - don't log raw request-parse errors — prompt-fragment privacy (#376) Coordinator LatestProviderVersion bump is intentionally deferred until the signed 0.6.12 bundle is published (prod uses the in-memory store, so the hardcoded fallback is authoritative after a redeploy).

Summary
Gemma-4 (
gemma-4-26b-qat-4bit) crash-loops on busy providers with[metal::malloc] Resource limit (499000) exceeded(≈ every 15 min on an M3Ultra with free RAM). This is a live Metal buffer-COUNT leak, not a
bytes/cache problem. This PR bounds the checkpoint KV-capture pipeline so the
live resource count plateaus instead of climbing to the ceiling.
Provider-only change. The
libs/mlx-swift*submodules are untouched.Target: 0.6.12.
Root cause (verified)
Gemma-4 is heterogeneous (sliding
[8,256]+ full[2,512]), so it uses the.checkpointprefix-cache tier, which is on by default (opt out withDARKBLOOM_PREFIX_CACHE=0):provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1029-1066—.checkpointtier setupprovider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1185-1188— prefix cache default-ON / opt-outThe capture hook, fired per checkpoint boundary, spawned an unbounded
detached Task:
provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1115-1124(production) and:821-825(test seam)The hook is fired synchronously on the engine queue with a freshly-extracted,
per-layer KV snapshot:
libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatching/Scheduler.swift:396-401—caches = pp.ppBatch.promptCache.map { $0.extractBatched(0) }Each spawned
Taskpins a full per-layer KV snapshot (liveMLXArrays,≈ layers × 2 Metal buffers) until
mgr.storeruns.PrefixCacheManageris asingle actor that serializes
storebehind AES-GCM serialize + fsync andagainst every
lookup/materialize:provider-swift/Sources/ProviderCore/KVCache/PrefixCacheManager.swift:752—func store(...)Under sustained traffic the actor falls behind, the capture Tasks queue, their
live snapshots accumulate, and the live Metal resource COUNT (independent of
bytes — see
Memory.numResources/Memory.resourceLimitinlibs/mlx-swift/Source/MLX/Memory.swift:199-222) climbs to theiogpu.rsrc_limitceiling (~499000) → crash.Why the prior mlx/mlx-c "count-aware" fixes can't fix this
Those fixes trim the cache (recycled, freed buffers) by making the trim
count-aware. But the snapshots held by the queued capture Tasks are LIVE,
not cached — they are still referenced, so the allocator cannot reclaim them no
matter how aggressively the cache is trimmed. The idle-gated
Memory.clearCache()also never fires under sustained load. The only fix is tobound the number of live snapshots retained in flight, which is what this PR
does.
The fix (provider-only)
Backpressure / bounded capture pipeline (primary). New
CheckpointCapturePipeline(BatchScheduler.swift→ newCheckpointCapturePipeline.swift): a bounded, single-consumerAsyncStream(
bufferingNewest(max-in-flight)) feeding one consumer Task that callsmgr.store.submitis synchronous/non-blocking and drops the surplussnapshot on full (released immediately, so its Metal buffers free). This
caps retained live snapshots to a small constant —
max-in-flight + 1(buffer + the one in the consumer) — regardless of how far behind the
manager actor falls. Default
max-in-flight = 2, env-tunable viaDARKBLOOM_KV_CAPTURE_MAX_INFLIGHT. Dropping is safe: capture is best-effortcache-warming, so a drop only costs a future cache miss, never correctness.
Admission gate under resource pressure (secondary, cheap). Before
enqueuing, skip capture when the live Metal resource count is high —
Memory.numResources > 0.7 × Memory.resourceLimit(guardsresourceLimit == 0). This stops feeding the leak exactly when it matters,and matches the engine's existing
[rsrc]70%-pressure threshold.Teardown drains/cancels.
stopCurrentEngine(and the superseded-loadbailouts) finish the stream and cancel the consumer, releasing any retained
snapshots so nothing leaks across model swaps. Ordered before the manager
flush so an in-flight
storecan't race the index flush / accountantderegister.
The decode path, KV-cache classes, and the manager's persistence logic are
unchanged; the only behavior change is bounding capture. Both capture-hook
sites (production builder + test seam) share one
makeCheckpointCaptureWiringhelper.
Tests
swift buildpasses; new + existing suites are green againstmaster(
v0.6.11) submodule pins:CheckpointCapturePipelineTests(4 tests):capturePipelineBoundsInFlightSnapshots— floods the pipeline against adeliberately-stalled consumer and asserts the number of retained snapshots
never exceeds the small constant bound (vs all N if unbounded), that
overflow is dropped not queued, and that nothing leaks after drain.
capturePipelineCapacityFloorIsOne— capacity clamps to ≥ 1.captureAdmissionGateThreshold— 70% threshold math incl. theresourceLimit == 0guard.captureMaxInFlightIsSmallAndPositive— default cap + env knob.BatchScheduler,PrefixCache,Continuous,Hybrid,KVCache— 226 tests pass (live model-download tests skip withoutDARKBLOOM_LIVE_MLX_TESTS=1).Validating in prod
Run a provider on Gemma-4 with the resource-count diagnostic (default-on; this
just makes the cadence explicit):
Watch the
[rsrc]log line (subsystemdev.darkbloom.provider, categoryrsrc). Before this change the liveresourcescount climbs monotonicallytoward 499000 under sustained traffic; after it should plateau well below
the limit. Optionally tune
DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT(default 2).Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.